from odoo import fields, models, api
from odoo.exceptions import UserError, ValidationError

from ...functions.operation_control_fc import OperationControlFC


class RPShipper(models.Model):
    _name = "rp.shipper"
    _description = '托运商'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _sql_constraints = [('unique_name', 'UNIQUE(name)', '托运商名称不能重复'),
                        ('unique_code', 'UNIQUE(code)', '托运商编码不能重复'),
                        ('unique_courier_id', 'UNIQUE(courier_id)', '一个承运商只能有一个托运商')]
    
    def _get_default_package_standards_ids(self):
        standards_ids = self.env['rp.package.standards'].search([('use_type','in',['all','shipper'])])
        return [(6,0,standards_ids.ids)]

    name = fields.Char(string='名称', required=True, copy=False, index=True, tracking=True)
    code = fields.Char(string='编号', default='New', readonly=True, copy=False, index=True, tracking=True)
    photo = fields.Binary(string='图片', tracking=True)

    courier_id = fields.Many2one(string='承运商', comodel_name='rp.courier', required=True, tracking=True)
    # country_group_ids = fields.Many2many(string='可达范围', comodel_name='res.country.group', related='rp_courier_id.ship_to_country_group_ids',
    #                                      relation='rp_shipper_template_and_country_group_rel', column1='shipper_template_id', column2='country_group_id')

    operation_display = fields.Char(string='头尾程', default='-,-,-,-', compute='_depends_fulfill_operation', store=True, tracking=True)
    operation_pickup = fields.Boolean(string='上门取件', default=False)
    operation_dropoff = fields.Boolean(string='网点收件', default=False)
    operation_delivery = fields.Boolean(string='送货上门', default=False)
    operation_collect = fields.Boolean(string='网点取件', default=False)

    package_type_ids = fields.Many2many(string='包裹类型', comodel_name='rp.package.type', relation='rp_shipper_and_package_type_rel', column1='shipper_id', column2='package_type_id', tracking=True)
    package_standards_ids = fields.Many2many(string='包裹标准', comodel_name='rp.package.standards',
                                             default=_get_default_package_standards_ids,
                                             relation='rp_shipper_and_package_standards_rel', column1='shipper_id', column2='package_standards_id')

    value_added_ids = fields.Many2many(string='增值服务', comodel_name='rp.value.added.service', relation='rp_shipper_and_value_added_rel', column1='shipper_id', column2='value_added_id', tracking=True)

    rp_shipper_mail_route_ids = fields.One2many(string='邮路明细', comodel_name='rp.shipper.mail.route', inverse_name='shipper_id', tracking=True)

    # 通过双向的m2o建立一对一关系
    sale_template_id = fields.Many2one(string='销售价模板', comodel_name='rp.shipper.sale.template', tracking=True)

    remarks = fields.Text(string='备注', tracking=True)

    @api.onchange('courier_id')
    def _onchange_fulfill_courier_info(self):
        if self.courier_id:
            self.update({'code': "'" + self.courier_id.code,
                         'photo': self.courier_id.photo,
                         'operation_pickup': True if self.courier_id.operation_pickup else False,
                         'operation_dropoff': True if self.courier_id.operation_dropoff else False,
                         'operation_delivery': True if self.courier_id.operation_delivery else False,
                         'operation_collect': True if self.courier_id.operation_collect else False,
                         'package_type_ids': [(6, 0, self.courier_id.package_type_ids.ids)],
                         'value_added_ids': [(6, 0, self.courier_id.value_added_ids.ids)]})

    @api.constrains('operation_pickup', 'operation_dropoff', 'operation_delivery', 'operation_collect')
    def _check_operation_info(self):
        for s in self:
            if s.courier_id:
                if all([s.courier_id.operation_pickup is False, s.operation_pickup is True]):
                    raise ValidationError('当前承运商不支持上门取件')
                if all([s.courier_id.operation_dropoff is False, s.operation_dropoff is True]):
                    raise ValidationError('当前承运商不支持网点收件')
                if all([s.courier_id.operation_delivery is False, s.operation_delivery is True]):
                    raise ValidationError('当前承运商不支持送货上门')
                if all([s.courier_id.operation_collect is False, s.operation_collect is True]):
                    raise ValidationError('当前承运商不支持网点取件')

    @api.depends('operation_pickup', 'operation_dropoff', 'operation_delivery', 'operation_collect')
    def _depends_fulfill_operation(self):
        for s in self:
            operation = OperationControlFC(self.env, s.operation_dropoff, s.operation_pickup, s.operation_collect, s.operation_delivery)

            s.write({'operation_display': operation.fulfill_display(),
                     'value_added_ids': [(6, 0, operation.update_value_add_list(s.value_added_ids.ids))]})

    @api.onchange('value_added_ids')
    def _onchange_value_added_ids(self):
        """ 头尾程的增值服务不允许删除 """
        if self.value_added_ids:
            operation = OperationControlFC(self.env, self.operation_dropoff, self.operation_pickup, self.operation_collect, self.operation_delivery)
            if not operation.monitor_value_add_list(self.value_added_ids.ids):
                raise UserError('增值服务中的头尾程不允许删除')

    @api.onchange('sale_template_id')
    def _onchange_cost_template(self):
        if self.sale_template_id:
            template_rcds = self.env['rp.shipper.sale.template'].search([('shipper_id', '=', self._origin.id)])
            for t in template_rcds:
                t.active_flag = False
            self.sale_template_id.active_flag = True

    @api.model_create_multi
    def create(self, vals_list):
        results = super(RPShipper, self).create(vals_list)
        for result in results:
            courier = self.env['rp.courier'].search([('id', '=', result.courier_id.id)], limit=1)
            courier.write({'shipper_id': result.id})
        return results

    def write(self, vals):
        courier = self.env['rp.courier'].search([('id', '=', vals.get('courier_id'))], limit=1) if vals.get('courier_id', False) else False
        result = super(RPShipper, self).write(vals)
        if courier:
            original_courier = self.env['rp.courier'].search([('id', '=', self.id)])
            original_courier.write({'shipper_id': False})
            courier.write({'shipper_id': self.id})
        return result

    def action_update_courier_line_info(self):
        """ 更新承运商邮路信息 """
        self.ensure_one()
        if self.courier_id and self.courier_id.courier_mail_route_ids:
            create_list = []
            for mr in self.courier_id.courier_mail_route_ids:
                rcd = self.rp_shipper_mail_route_ids.filtered(lambda r: r.courier_mail_route_id.id == mr.id)
                if not rcd:
                    create_values = {'name': mr.name,
                                     'code': "'" + mr.code,
                                     'courier_mail_route_id': mr.id,
                                     'operation_display': True if mr.operation_pickup else False,
                                     'operation_pickup': True if mr.operation_pickup else False,
                                     'operation_dropoff': True if mr.operation_dropoff else False,
                                     'operation_delivery': True if mr.operation_delivery else False,
                                     'package_type_ids': [(6, 0, mr.package_type_ids.ids)],
                                     'aging_ids': [(6, 0, mr.aging_ids.ids)],
                                     'ship_from_country_group_ids': [(6, 0, mr.ship_from_country_group_ids.ids)],
                                     'ship_to_country_group_ids': [(6, 0, mr.ship_to_country_group_ids.ids)]}
                    create_list.append((0, 0, create_values))
            self.write({'rp_shipper_mail_route_ids': create_list})
